package com.woniu.humanresource.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.woniu.humanresource.dao.ActivityDao;
import com.woniu.humanresource.dao.EmpInfoDao;
import com.woniu.humanresource.dao.EmployeesDao;
import com.woniu.humanresource.dao.InterviewerDao;
import com.woniu.humanresource.entity.*;
import com.woniu.humanresource.listener.EmpListener;
import com.woniu.humanresource.service.EmployeesService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class EmployeesServiceImpl implements EmployeesService {
    @Resource
    EmployeesDao employeesDao;
    @Resource
    EmpInfoDao empInfoDao;
    @Resource
    InterviewerDao interviewerDao;
    @Resource
    ActivityDao activityDao;
    @Value("${upload.addResourceLocation}")
    private String addResourceLocation;
    @Value("${download.url}")
    private String downloadUrl;

    @Override
    public void insertEmployees(Employees employees) {
        EmployeeInformation employeeInformation = new EmployeeInformation();
        employeeInformation.setChannel(employees.getChannel());
        employeeInformation.setIdNum(employees.getIdNum());
        employeeInformation.setDate(employees.getDate());
        employeeInformation.setDepartment(employees.getDepartment());
        employeeInformation.setCurrentAddress(employees.getCurrentAddress());
        employeeInformation.setEmergencyContact(employees.getEmergencyContact());
        employeeInformation.setEmergencyContactNumber(employees.getEmergencyContactNumber());
        employeeInformation.setHouseholdAddress(employees.getHouseholdAddress());
        employeeInformation.setHeadImg(employees.getHeadImg());
        employeeInformation.setNational(employees.getNational());
        employeeInformation.setRecord(employees.getRecord());
        employeeInformation.setSchool(employees.getSchool());
        employeeInformation.setState(employees.getState());
        employeeInformation.setType(employees.getType());
        empInfoDao.insertEmpInfo(employeeInformation);
//            对应eid
        employees.setEid(employeeInformation.getId());
        employeesDao.insertEmployees(employees);
    }

    @Override
    public PageBean<Employees> selectEmpInfoCondition(Employees employees, int pageIndex, int pageSize) {
        List<Employees> employees1 = employeesDao.selectEmpInfoCondition(employees, pageIndex, pageSize);
        //        封装为PageBean对象，并设置属性
        PageBean<Employees> pageBean=new PageBean<>();
        pageBean.setBeanList(employees1);
        pageBean.setPageSize(pageSize);
        pageBean.setPageIndex(pageIndex);
        pageBean.setBeginEnd();
        pageBean.setTotalRecord(selectConditionCount(employees));
        return pageBean;
    }

    @Override
    public int selectConditionCount(Employees employees) {
        int count = employeesDao.selectConditionCount(employees);
        return count;
    }

    @Override
    public void deleteEmployees(int id) {
        employeesDao.deleteEmployees(id);
    }

    @Override
    public void updateEmployees(Employees employees) {
        employeesDao.updateEmployees(employees);
    }

    @Override
    public void importEmployees(MultipartFile empExcel) {
//        上传文件创建文件路径
        DateFormat dateFormat=new SimpleDateFormat("yyyy.MM.dd");
        String dateStr = dateFormat.format(new Date());
        File file1 = new File(addResourceLocation+"empExcel."+dateStr);
        if(!file1.exists()){
            file1.mkdirs();
        }
        String path=addResourceLocation+"empExcel."+dateStr;
        File file = new File(path, UUID.randomUUID()+empExcel.getOriginalFilename());

        try {
            empExcel.transferTo(file);
//            读取文件数据
            ExcelReaderBuilder workBook = EasyExcel.read(file.getPath(), Employees.class, new EmpListener());
            ExcelReaderSheetBuilder sheet = workBook.sheet();
            sheet.doRead();
//            获得解析的员工集合
            List<Employees> employeeList = EmpListener.getEmployeeList();
            EmployeeInformation employeeInformation = new EmployeeInformation();
//            遍历添加到数据库
            for(Employees employee:employeeList) {
                employeeInformation.setChannel(employee.getChannel());
                employeeInformation.setIdNum(employee.getIdNum());
                employeeInformation.setDate(employee.getDate());
                employeeInformation.setDepartment(employee.getDepartment());
                employeeInformation.setCurrentAddress(employee.getCurrentAddress());
                employeeInformation.setEmergencyContact(employee.getEmergencyContact());
                employeeInformation.setEmergencyContactNumber(employee.getEmergencyContactNumber());
                employeeInformation.setHouseholdAddress(employee.getHouseholdAddress());
                employeeInformation.setHeadImg(employee.getHeadImg());
                employeeInformation.setNational(employee.getNational());
                employeeInformation.setRecord(employee.getRecord());
                employeeInformation.setSchool(employee.getSchool());
                employeeInformation.setState(employee.getState());
                employeeInformation.setType(employee.getType());
                empInfoDao.insertEmpInfo(employeeInformation);
//            对应eid
                employee.setEid(employeeInformation.getId());
                employeesDao.insertEmployees(employee);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportEmployeeExcel(HttpServletResponse response) {
        List<Employees> employees = employeesDao.selectAll();
        try {
            ExcelWriterBuilder workBook = EasyExcel.write(downloadUrl, Employees.class);
            // sheet方法参数： 工作表的顺序号（从0开始）或者工作表的名字
            workBook.sheet("员工信息").doWrite(employees);
//            downloadTempalate(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //    获取活动信息
    @Override
    public List<Activity> getEmpActivity(int id) {
//        获取电话号码
        Employees employees = new Employees();
        employees.setId(id);
        List<Employees> employees1 = employeesDao.selectEmpInfoCondition(employees, 1, 1);
        Employees employees2 = employees1.get(0);
        String telephone = employees2.getTelephone();
//        查询面试者信息
        Interviewer interviewer = new Interviewer();
        interviewer.setTelephone(telephone);
        List<Interviewer> interviewers = interviewerDao.selectCondition(interviewer,1,1);
        if(interviewers.isEmpty()){
            return null;
        }else {
            Interviewer interviewer1 = interviewers.get(0);
//          查询变更信息
            List<Activity> activities = activityDao.selectActivity(interviewer1.getId());
            return activities;
        }

    }


//    public  void downloadTempalate(HttpServletResponse response) throws IOException {
//        // 告诉浏览器用什么软件可以打开此文件
////        response.setHeader("content-Type", "application/vnd.ms-excel");
//        // 下载文件的默认名称
////        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("员工信息.xlsx", "utf-8"));
//        //4. 创建输入、输出流
//        FileInputStream input = new FileInputStream(downloadUrl);
//        ServletOutputStream sos = response.getOutputStream();
//
//        //IO流获取文件的字节流，然后再响应给浏览器
//        byte[] arr = new byte[1024];
//        int res = 0;
//        while((res = input.read(arr)) > 0){
//            //将读取的内容输出到输出流中
//            sos.write(arr, 0, res);
//        }
//        input.close();
//        sos.close();
//    }


}
